import React, { useEffect, useState } from "react";
import { useRef } from "react";
import BulletScreen, { StyledBullet } from 'rc-bullets';
import style from "./style.module.css"

const UseCamera = (props) => {
    // 弹幕屏幕
    const [screen, setScreen] = useState(null);
    // 弹幕内容
    const [bullet, setBullet] = useState('');
    useEffect(() => {
        // 给页面中某个元素初始化弹幕屏幕，一般为一个大区块
        let s = new BulletScreen('.screen');
        // or
        // let s=new BulletScreen(document.querySelector('.screen));
        setScreen(s);
    }, []);

    // 弹幕内容输入事件处理
    const handleChange = ({ target: { value } }) => {
        setBullet(value);
    };
    // 发送弹幕
    const handleSend = () => {
        if (bullet) {
            // push
            // or 使用 StyledBullet
            screen.push(
                <StyledBullet
                    head="https://zerosoul.github.io/rc-bullets/assets/img/heads/girl.jpg"
                    msg={bullet}
                />
            );
        }
    };

    //直播摄像头
    let video_ref = useRef();

    const hanlefhCamera = () => {
        props.history.push('/layout/liveManage')
    }

    //开启摄像头
    async function getMedia() {
        let video = video_ref.current;
        let constraints = {
            video: { width: 600, height: 500 },
            audio: true,
        };

        try {
            let MediaStream = await navigator.mediaDevices.getUserMedia(constraints);
            video.srcObject = MediaStream;
            video.play();
        } catch (e) {
            alert(e);
        }
    }

    //关闭摄像头
    const handleClose = () => {
        let video = video_ref.current;
        console.log(video);
        // video.srcObject.stop()
        video.srcObject.getTracks()[1].stop()
        console.log(video.srcObject.getTracks());
    }

    useEffect(() => {

    }, []);

    return (
        <div className={style.cameraBox}>
            <div style={{ display: "flex", flexDirection: "column" }}>
                <video
                    ref={video_ref}
                    height="660px"
                    autoPlay={true}
                ></video>
                <br />
                <div className={style.btnBox}>
                    <button className={style.btnlive} onClick={() => { getMedia() }}>打开摄像头</button>
                    <button className={style.btnlive} onClick={() => { handleClose() }}>关闭摄像头</button>
                    <button className={style.liveFhBox} onClick={() => hanlefhCamera()}>返回</button>
                </div>
            </div>

            <div className={style.screenBox}>
                <div className="screen" style={{ width: '450px', height: '550px' }}></div>
                <input value={bullet} onChange={handleChange} className={style.iptBox}/>
                <button onClick={handleSend} className={style.transmit}>发送</button>
            </div>
        </div>
    );
};

export default UseCamera